import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

class Message{
    public String from;
    public String to;
    public String words;
}

@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    //private List<Message> messageList = new ArrayList<>();
    //private String filePath = "C:\\ConfessionWall.txt";
    //从服务器获取到数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");

        List<Message> messageList = load();
        //这里的writeValue就是吧messageList里面的对象转换成Json格式并且写入到resp.getWriter里
        objectMapper.writeValue(resp.getWriter(),messageList);
    }
    private List<Message> load(){
        List<Message> messageList = new ArrayList<>();
        /*
        System.out.println("向文件中读取数据");
        //我们需要按行读取，FileReader本身不支持，需要套一层BufferedReader
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))){
            while(true){
                String line = bufferedReader.readLine();
                if(line==null){
                    break;
                }
                String[] tokens = line.split("\t");
                Message message = new Message();
                message.from=tokens[0];
                message.to=tokens[1];
                message.words=tokens[2];
                messageList.add(message);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        */
        System.out.println("向数据库中读取数据");
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "select * from ConfessionWall";
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            while(resultSet.next()){
                Message message = new Message();
                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.words = resultSet.getString("words");
                messageList.add(message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return messageList;
    }
    //从客户端提交数据
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");

        //这里获取到Json的数据并且用一个Message.class接收
        Message message = objectMapper.readValue(req.getInputStream(),Message.class);
        //messageList.add(message);
        save(message);
        resp.getWriter().write("{\"ok\":1}");
    }
    private void save(Message message){
        /*
        //表示以追加的方式将filePath的文件进行写操作
        System.out.println("向文件中插入数据");
        try (FileWriter fileWriter = new FileWriter(filePath,true)){
            fileWriter.write(message.from+"\t"+message.to+"\t"+message.words+"\n");
        }catch (IOException e){
            e.printStackTrace();
        }
        */
        //先和数据库建立连接
        System.out.println("向数据库中插入数据");
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            //先和数据库建立连接
            connection = DBUtil.getConnection();
            //构造拼装SQL
            String sql = "insert into ConfessionWall values (?, ?, ?);";
            statement = connection.prepareStatement(sql);
            statement.setString(1,message.from);
            statement.setString(2,message.to);
            statement.setString(3,message.words);
            //执行SQL
            int ret = statement.executeUpdate();

            if(ret==1){
                System.out.println("插入成功");
            }else{
                System.out.println("插入失败");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,statement,null);
        }
    }
}
